package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.*;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.ThreadLocalUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class SettingsService {

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingApi settingApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //查询通用设置
    public SettingsVo settings() {
        SettingsVo settingsVo = new SettingsVo();

        //1.获取用户id
        Long userId = ThreadLocalUtils.getUserId();
        settingsVo.setId(userId);
        //2.获取用户手机号码
        String userPhone = ThreadLocalUtils.getUserPhone();
        settingsVo.setPhone(userPhone);

        //3.查询陌生人问题
        Question question =questionApi.queryQuestion(userId);//根据用户id查询Question对象
        String txt = question == null ? "你喜欢java吗？" : question.getTxt();//三元运算符
        settingsVo.setStrangerQuestion(txt);

        //4.查询通用设置通知开关

        Settings settings =settingApi.selectSettings(userId);

        if(settings != null){
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
        }
        return settingsVo;
    }

    //设置陌生人问题
    public void setQuestion(String content) {

        //1.获取用户id
        Long userId = ThreadLocalUtils.getUserId();
        //2.根据用户id查询陌生人问题
        Question question = questionApi.queryQuestion(userId);
        if(question == null){
            //不存在，保存数据
            question =new Question();
           question.setUserId(userId);
            question.setTxt(content);
            questionApi.saveQuestion(question);
        }else{
            //存在
            question.setTxt(content);
            questionApi.updateQuestion(question);
        }
    }




    //通知设置
    public void setNotification(Map map) {
        Boolean likeNotification = (Boolean) map.get("likeNotification");
        Boolean pinglunNotification = (Boolean) map.get("pinglunNotification");
        Boolean gonggaoNotification = (Boolean) map.get("gonggaoNotification");
        //1.获取用户id
        Long userId = ThreadLocalUtils.getUserId();
        //2.调用api根据用户id查询Settings
        Settings settings = settingApi.selectSettings(userId);
        if(settings == null){
            //不存在，帮他保存到数据库
            settings =new Settings();
            settings.setUserId(userId);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingApi.save(settings);
        }else{
            //存在，更新
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingApi.update(settings);
        }
    }




    //黑名单列表分页查询
    public PageResult queryBlacklist(int page, int pageSize) {
        //1.获取用户id
        Long userId = ThreadLocalUtils.getUserId();
        //2.调用api根据用户id查询用户的黑名单列表
        IPage<UserInfo> blacklist =blackListApi.queryBlacklist(userId,page,pageSize);
        //3.从Ipage对象获取 PageResult对象所需的数据
        PageResult pageResult = new PageResult(page,pageSize, (int) blacklist.getTotal(),blacklist.getRecords());
        return pageResult;
    }

    //取消黑名单
    public void deleteBlackList(Long blackUserId) {
        //1.获取用户id
        Long userId = ThreadLocalUtils.getUserId();
        blackListApi.deleteBlack(userId,blackUserId);
    }



    //修改手机号码获取验证码
    public String updateUserPhone() {
        //1.获取手机号码
        String userPhone = ThreadLocalUtils.getUserPhone();
        //2.生成六位随机数字
        String randomCode = RandomStringUtils.randomNumeric(6);

        //3.把随机数缓存进Redis
        redisTemplate.opsForValue().set("Code_"+userPhone, randomCode, Duration.ofMinutes(5));

       return randomCode;
    }



    //校验验证码：
    public Map verificationCode(String verificationCode,String userPhone) {


        //1.从Redis中获取验证码
        String randomCode = redisTemplate.opsForValue().get("Code_" + userPhone);

        //2.校验验证码
        if(StringUtils.isEmpty(verificationCode) || !randomCode.equals(verificationCode)){
            throw new BusinessException(ErrorResult.loginError());
        }

        Boolean result = true;

        Map resultMap = new HashMap();
        resultMap.put("verification", result);
        return resultMap;
    }


    //保存新手机号码
    public void savaUserPhone(Map map) {

        //1.获取要保存的新手机号码
        String newPhone = (String) map.get("phone");
        //2.获取用户id
        Long userId = ThreadLocalUtils.getUserId();

        User user = new User();
        user.setId(userId);
        user.setMobile(newPhone);

        //3.调用api根据用户id修改手机号码
        userApi.updateUserPhone(user);

    }
}
